app.service("commonService", function ($http, $filter, $rootScope, $modal, $location, $window, APP_CONST, toaster) {
    var ajaxByString = function (url, data) {
        return $http({
            method: 'POST',
            url: url,
            data: data,
            headers: {
                'Content-Type': "application/x-www-form-urlencoded;charset=utf-8"
            }
        })
    };
    var ajaxByObject = function (url, data) {
        return $http({
            method: 'POST',
            url: url,
            data: data,
            headers: {
                'Content-Type': "application/json;charset=utf-8"
            }
        })
    };

    var reloadTable = function (type, key) {
        if (key == null) {
            return;
        }
        var table = $('#' + key + 'Table').dataTable();
        if (type == "new") {
            table.fnReloadAjax();
        } else {
            table.fnReloadAjax(false, null, true);
        }
    };
    return {
        type: "",
        menuCode: "",
        param: {},
        editData: function (str, type) {
            this.type = type;
            $rootScope.$broadcast(str);
        },
        editDataWithState: function (param, type) {
            this.type = type;
            this.param = param;
        },
        openEditDialog: function (param, url, ctrl) {
            return $modal.open({
                templateUrl: url,
                controller: ctrl,
                windowClass: 'confirmDialog',
                size: 'lg',
                backdrop: 'static',
                resolve: {
                    param: function () {
                        return param;
                    }
                }
            });
        },
        openListDialog: function (param, url, ctrl) {
            return $modal.open({
                templateUrl: url,
                controller: ctrl,
                windowClass: 'confirmDialog',
                size: 'lg',
                backdrop: 'static',
                resolve: {
                    param: function () {
                        return param;
                    }
                }
            });
        },
        httpText: function (url, data) {
            return ajaxByString(url, data);
        },
        httpJson: function (url, data) {
            return ajaxByObject(url, data);
        },
        getSelectData: function (tbID, rowID, key) {
            var table = $('#' + tbID).dataTable();
            var rows = table.fnGetNodes();

            for (var i = 0; i < rows.length; i++) {
                var data = table.fnGetData(rows[i]);
                if ($("#" + rowID + data[key]).is(':checked')) {
                    return data;
                }
            }
            return null;
        },
        getSelectDataByIdentity: function (key, id_field_name) {
            var table = $('#ltc' + key + 'Table').dataTable();
            var rows = table.fnGetNodes();
            var result = {};
            for (var i = 0; i < rows.length; i++) {
                var data = table.fnGetData(rows[i]);
                if ($("#ck_" + key + data[id_field_name]).is(':checked')) {
                    result = data;
                }
            }
            return result;
        },
        getSelectDatas: function (key) {
            var table = $('#' + key + 'Table').dataTable();
            var rows = table.fnGetNodes();
            var result = [];
            for (var i = 0; i < rows.length; i++) {
                var data = table.fnGetData(rows[i]);
                if ($("#" + key + "_select_" + data.id).is(':checked')) {
                    result.push(data);
                }
            }
            return result;
        },
        getSelectIds: function (key) {
            var table = $('#' + key + 'Table').dataTable();
            var rows = table.fnGetNodes();
            var result = "";
            for (var i = 0; i < rows.length; i++) {
                var data = table.fnGetData(rows[i]);
                if ($("#" + key + "_select_" + data.id).is(':checked')) {
                    result += data.id + ",";
                }
            }
            return result;
        },
        tableFirstCol: function (key) {
            return {
                aTargets: [0],
                mRender: function (data, type, full) {
                    var editId = key + "_select_" + data;
                    return '<label class="i-checks m-b-none"><input id = "' + editId + '" class="select' + key + '" type="checkbox"><i></i></label>';
                }
            };
        },
        tableColStatus: function (num, statusArray, statusStrArray) {
            return {
                aTargets: [num],
                mRender: function (data, type, full) {
                    if (data == null) {
                        return "-";
                    }
                    for (var i = 0; i < statusArray.length; i++) {
                        if (statusArray[i] == data) {
                            return statusStrArray[i];
                        }
                    }
                    return "";
                }
            };
        },

        tableRowAllowNull: function (num) {
            return {
                aTargets: [num],
                mRender: function (data, type, full) {
                    if (data == null) {
                        return "";
                    } else {
                        return data;
                    }
                }
            };
        },
        tableRowAllowNullNoSort: function (num) {
            return {
                aTargets: [num],
                mRender: function (data, type, full) {
                    if (data == null) {
                        return "";
                    } else {
                        return data;
                    }
                },
                bSortable: false
            };
        },
        tableColDate: function (num, format) {
            return {
                aTargets: [num],
                mRender: function (data, type, full) {
                    if (data == null) {
                        return "";
                    } else {
                        return $filter('date')(new Date(data), format);
                    }
                }
            };
        },
        tableColDateDefault: function (num) {
            return this.tableColDate(num, "yyyy-MM-dd");
        },
        isEnterKey: function (e) {
            var keycode = window.event ? e.keyCode : e.which;
            return keycode == 13;
        },
        unique: function (data) {
            var n = {}, r = []; //n为hash表，r为临时数组
            for (var i = 0; i < data.length; i++) //遍历当前数组
            {
                if (!n[data[i]]) //如果hash表中没有当前项
                {
                    n[data[i]] = true; //存入hash表
                    r.push(data[i]); //把当前数组的当前项push到临时数组里面
                }
            }
            return r;
        },
        isEmpty: function (data) {
            return data == null || data == "" || data == undefined
        },
        getMenus: function (menuCode) {
            var buttons = [];
            for (var i = 0; i < $rootScope.permissionTree.length; i++) {
                if ($rootScope.permissionTree[i].parentCode == menuCode) {
                    buttons.push($rootScope.permissionTree[i]);
                }
            }
            return buttons;
        },
        getParentCode: function () {
            var stateUrl = $location.path().replace(/\//g, ".").substr(1, $location.path().length);
            for (var i = 0; i < $rootScope.permissionTree.length; i++) {
                var url = $rootScope.permissionTree[i].url;
                if ($rootScope.permissionTree[i].childUrl != null && $rootScope.permissionTree[i].childUrl != "") {
                    var child = $rootScope.permissionTree[i].childUrl.split(",");
                    for (var j = 0; j < child.length; j++) {
                        url += "." + child[j];
                        if (url == stateUrl) {
                            return $rootScope.permissionTree[i].code;
                        }
                    }
                } else {
                    if ($rootScope.permissionTree[i].url == stateUrl) {
                        return $rootScope.permissionTree[i].code;
                    }
                }
            }
        },
        confirmAction: function (url, data, type, typeStr, name, key) {
            BootstrapDialog.confirm("确认" + typeStr + name + "？", function (result) {
                if (result) {
                    ajaxByString(url, data).success(function (data) {
                        if (data.status) {
                            reloadTable(type, key);
                            toaster.pop("success", "成功", typeStr + name + "成功");
                        } else {
                            toaster.pop("error", "错误", data.message);
                        }
                    })
                }
            });
        },
        reloadTable: function (type, key) {
            return reloadTable(type, key);
        },
        datePicker: function (scope) {
            scope.clear = function () {
                $scope.dt = null;
            };
            scope.disabled = function (date, mode) {
                return ( mode === 'day' && ( date.getDay() === 0 || date.getDay() === 6 ) );
            };
            scope.toggleMin = function () {
                scope.minDate = scope.minDate ? null : new Date();
            };
            scope.toggleMin();

            scope.dateOptions = {
                formatYear: 'yy',
                startingDay: 1,
                class: 'datepicker'
            };
            scope.formats = ['dd-MMMM-yyyy', 'yyyy-MM-dd', 'dd.MM.yyyy', 'shortDate'];
            scope.format = scope.formats[1];
        },
        toasterInfo: function (msg) {
            toaster.pop("info", "信息提示", msg);
        },
        toasterSuccess: function (msg) {
            toaster.pop("success", "操作成功", msg);
        },
        toasterWarn: function (msg) {
            toaster.pop("Warning", "操作提示", msg);
        },
        toasterWait: function (msg) {
            toaster.pop("Wait", "正在操作", msg);
        },
        toasterError: function (msg) {
            toaster.pop("error", "信息提示", msg);
        }

    }
});
